/**
 * Notes: 用户管理
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 * Date: 2022-01-22  07:48:00 
 */

const BaseProjectAdminService = require('./base_project_admin_service.js');

const util = require('../../../../framework/helpers/util.js');
const exportUtil = require('../../../../framework/helpers/export_util.js');
const timeUtil = require('../../../../framework/helpers/time_util.js');
const dataUtil = require('../../../../framework/helpers/data_util.js');
// 使用统一配置入口引用模型
const OAModelsConfig = require('../config/models_config');
const { UserModel } = OAModelsConfig;
const AdminHomeService = require('./admin_home_service.js');

// 导出用户数据KEY
const EXPORT_USER_DATA_KEY = 'EXPORT_USER_DATA';

class AdminUserService extends BaseProjectAdminService {

	async editUser(userId, data) {
		let where = {
			_id: userId,
			_pid: this.getProjectId() //添加项目ID条件
		}
		let user = await UserModel.getOne(where);
		if (!user) {
			this.AppError('用户不存在');
		}

		// 更新用户数据
		let updateData = {
			USER_NAME: data.name,
			USER_MOBILE: data.mobile,
			USER_DEPT: data.dept,
			USER_AUTH: data.auth,
			USER_FORMS: data.forms,
			USER_EDIT_TIME: this._timestamp,
			USER_EDIT_IP: this._ip
		};

		await UserModel.edit(where, updateData);

		return {
			id: userId
		};
	}

	/** 获得某个用户信息 */
	async getUser({userId, fields = '*'}) {
		let where = {
			_id: userId,
			_pid: this.getProjectId()
		}
		return await UserModel.getOne(where, fields);
	}

	/** 取得用户分页列表 */
	async getUserList({
		search, // 搜索条件
		sortType, // 搜索菜单
		sortVal, // 搜索菜单
		orderBy, // 排序
		whereEx, //附加查询条件 
		page,
		size,
		oldTotal = 0
	}) {

		orderBy = orderBy || {
			USER_ADD_TIME: 'desc'
		};
		let fields = '*';


		let where = {};
		where.and = {
			_pid: this.getProjectId() //复杂的查询在此处标注PID
		};

		if (util.isDefined(search) && search) {
			where.or = [{
				USER_NAME: ['like', search]
			},
			{
				USER_MOBILE: ['like', search]
			},
			{
				USER_MEMO: ['like', search]
			},
			];

		} else if (sortType && util.isDefined(sortVal)) {
			// 搜索菜单
			switch (sortType) {
				case 'dept':
					where.and.USER_DEPT = sortVal;
					break;
				case 'auth':
					where.and.USER_AUTH = Number(sortVal);
					break;
				case 'status':
					where.and.USER_STATUS = Number(sortVal);
					break;
				case 'sort': {
					orderBy = this.fmtOrderBySort(sortVal, 'USER_ADD_TIME');
					break;
				}
			}
		}
		let result = await UserModel.getList(where, fields, orderBy, page, size, true, oldTotal, false);


		// 为导出增加一个参数condition
		result.condition = encodeURIComponent(JSON.stringify(where));

		return result;
	}

	async statusUser(id, status, reason) {
		let where = {
			USER_MINI_OPENID: id,
			_pid: this.getProjectId()
		}

		let user = await UserModel.getOne(where);
		if (!user) {
			this.AppError('用户不存在');
		}

		let data = {
			USER_STATUS: status,
			USER_CHECK_REASON: reason,
			USER_EDIT_TIME: this._timestamp,
			USER_EDIT_IP: this._ip
		}

		await UserModel.edit(where, data);
	}

	/**删除用户 */
	async delUser(id) {
		let where = {
			_id: id,
			_pid: this.getProjectId()
		}

		let user = await UserModel.getOne(where);
		if (!user) {
			this.AppError('用户不存在');
		}

		await UserModel.del(where);
	}

	// #####################导出用户数据

	/**获取用户数据 */
	async getUserDataURL() {
		return await exportUtil.getExportDataURL(EXPORT_USER_DATA_KEY);
	}

	/**删除用户数据 */
	async deleteUserDataExcel() {
		return await exportUtil.deleteDataExcel(EXPORT_USER_DATA_KEY);
	}

	/**导出用户数据 */
	async exportUserDataExcel(condition, fields) {
		condition = JSON.parse(decodeURIComponent(condition));

		let where = condition;
		let orderBy = {
			USER_ADD_TIME: 'desc'
		};

		// 取得数据
		let list = await UserModel.getAll(where, '*', orderBy);
		let total = list.length;

		// 表头
		let header = [];
		for (let k = 0; k < fields.length; k++) {
			header.push(fields[k].title);
		}

		// 数据
		let data = [];
		data.push(header);

		for (let k = 0; k < list.length; k++) {
			let node = [];
			for (let j = 0; j < fields.length; j++) {
				let field = fields[j];
				let val = '';

				// 字段映射
				switch (field.mark) {
					case 'name':
						val = list[k].USER_NAME;
						break;
					case 'mobile':
						val = list[k].USER_MOBILE;
						break;
					case 'dept':
						val = list[k].USER_DEPT;
						break;
					case 'no':
						val = list[k].USER_OBJ.no;
						break;
					case 'zhiwu':
						val = list[k].USER_OBJ.zhiwu;
						break;
					case 'status':
						val = UserModel.getDesc('STATUS', list[k].USER_STATUS);
						break;
					case 'auth':
						val = list[k].USER_AUTH == 1 ? '是' : '否';
						break;
					case 'add_time':
						val = timeUtil.timestamp2Time(list[k].USER_ADD_TIME);
						break;
					case 'login_time':
						val = list[k].USER_LOGIN_TIME ? timeUtil.timestamp2Time(list[k].USER_LOGIN_TIME) : '未登录';
						break;
					default:
						val = '';
				}

				node.push(val || '未填写');
			}
			data.push(node);
		}

		// 导出数据
		return await exportUtil.exportDataExcel(EXPORT_USER_DATA_KEY, '员工资料', total, data);
	}

}

module.exports = AdminUserService;